import pygame
from settings import *
from support import import_folder
from sprites import Generic
from random import randint, choice

class Sky:
	def __init__(self):
		self.display_surface = pygame.display.get_surface()
		self.full_surf = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
		self.start_color = [255, 255, 255]  # 初始颜色为白色
		self.end_color = (38, 101, 189)  # 结束颜色为深蓝色

	def display(self, dt):
		for index, value in enumerate(self.end_color):
			if self.start_color[index] > value:
				self.start_color[index] -= 2 * dt  # 在每个帧中，逐渐减小初始颜色的值，实现淡出效果

		self.full_surf.fill(self.start_color)  # 使用初始颜色填充表面
		self.display_surface.blit(self.full_surf, (0, 0), special_flags=pygame.BLEND_RGBA_MULT)  # 在显示表面上绘制渐变背景

class Drop(Generic):
	def __init__(self, surf, pos, moving, groups, z):
		# 一般设置
		super().__init__(pos, surf, groups, z)
		self.lifetime = randint(400, 500)  # 随机产生雨滴的寿命
		self.start_time = pygame.time.get_ticks()  # 记录雨滴创建的时间

		# 移动设置
		self.moving = moving  # 标志雨滴是否移动
		if self.moving:
			self.pos = pygame.math.Vector2(self.rect.topleft)  # 雨滴的位置
			self.direction = pygame.math.Vector2(-2, 4)  # 移动的方向
			self.speed = randint(200, 250)  # 移动的速度

	def update(self, dt):
		# 移动
		if self.moving:
			self.pos += self.direction * self.speed * dt
			self.rect.topleft = (round(self.pos.x), round(self.pos.y))

		# 定时器
		if pygame.time.get_ticks() - self.start_time >= self.lifetime:
			self.kill()  # 当雨滴寿命结束时，将其移除精灵组

class Rain:
	def __init__(self, all_sprites):
		self.all_sprites = all_sprites
		self.rain_drops = import_folder('../graphics/rain/drops/')  # 导入雨滴的图像
		self.rain_floor = import_folder('../graphics/rain/floor/')  # 导入地面的图像
		self.floor_w, self.floor_h = pygame.image.load('../graphics/world/ground.png').get_size()  # 获取地面图像的尺寸

	def create_floor(self):
		Drop(
			surf=choice(self.rain_floor),  # 随机选择地面图像
			pos=(randint(0, self.floor_w), randint(0, self.floor_h)),  # 随机选择地面的位置
			moving=False,  # 地面不移动
			groups=self.all_sprites,  # 添加到精灵组中
			z=LAYERS['rain floor'])  # 设置图层

	def create_drops(self):
		Drop(
			surf=choice(self.rain_drops),  # 随机选择雨滴图像
			pos=(randint(0, self.floor_w), randint(0, self.floor_h)),  # 随机选择雨滴的位置
			moving=True,  # 雨滴移动
			groups=self.all_sprites,  # 添加到精灵组中
			z=LAYERS['rain drops'])  # 设置图层

	def update(self):
		self.create_floor()  # 创建地面
		self.create_drops()  # 创建雨滴
